package com.spreedairy.category;

import java.io.IOException;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletSession;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.kernel.dao.orm.DynamicQuery;
import com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil;
import com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.Constants;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.PortalClassLoaderUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.security.auth.PrincipalException;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.ServiceContextFactory;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portlet.shopping.CategoryNameException;
import com.liferay.portlet.shopping.NoSuchCategoryException;
import com.liferay.portlet.shopping.model.ShoppingCategory;
import com.liferay.portlet.shopping.service.ShoppingCategoryLocalServiceUtil;
import com.liferay.portlet.shopping.service.ShoppingCategoryServiceUtil;
import com.spreedairy.common.CommonAction;
import com.spreedairy.portal.NoSuchCustomFieldException;
import com.spreedairy.portal.model.CustomField;
import com.spreedairy.portal.model.impl.CustomFieldImpl;
import com.spreedairy.portal.service.CustomFieldLocalServiceUtil;

public class CategoryPortlet extends CommonAction{
	@Override
	public void doView(RenderRequest renderRequest,
			RenderResponse renderResponse) throws IOException, PortletException {
		String cmd = ParamUtil.getString(renderRequest, "action");
		
		
		/*if(Validator.isNotNull(cmd)){
			if(cmd.equalsIgnoreCase("defineField")) {
				
				viewJSP = "/html/category/define_field.jsp";
				
			}else {
				
				viewJSP = "/html/category/category_list.jsp"; 
			}
		}*/
		super.doView(renderRequest, renderResponse);
	}

	public void updateProcess(ActionRequest actionRequest,
			ActionResponse actionResponse) throws Exception {
		String cmd = ParamUtil.getString(actionRequest, Constants.CMD);
		String categoryId = ParamUtil.getString(actionRequest, "categoryId");
		PortletSession psession = actionRequest.getPortletSession();	
		psession.setAttribute("categoryId",categoryId, PortletSession.APPLICATION_SCOPE);
		try {
			if (cmd.equals(Constants.ADD) || cmd.equals(Constants.UPDATE)) {
				updateCategory(actionRequest);
			}
			else if (cmd.equals(Constants.DELETE)) {
				deleteCategory(actionRequest,actionResponse);
			}
			else if (cmd.equals(Constants.SEARCH)){
				categoryOrders(actionRequest, actionResponse);
				
			}
			

			//sendRedirect(actionRequest, actionResponse);
		}
		catch (Exception e) {
			if (e instanceof NoSuchCategoryException ||
				e instanceof PrincipalException) {

				SessionErrors.add(actionRequest, e.getClass().getName());
				e.printStackTrace();
				//setForward(actionRequest, "portlet.shopping.error");
			}
			else if (e instanceof CategoryNameException) {
				SessionErrors.add(actionRequest, e.getClass().getName());
				e.printStackTrace();
			}
			else {
				e.printStackTrace();
				throw e;
			}
		}
	}

	protected void deleteCategory(ActionRequest actionRequest,ActionResponse actionResponse)
		throws Exception {
		long categoryId = ParamUtil.getLong(actionRequest, "categoryId", 0l);
		String DelCategory=ParamUtil.getString(actionRequest, "DelCategory");
		System.out.println("delcategory >>>>>>>>>>>>>>>>>>>>>>>>>>>???????????????????????????");
		String[] categoryIds = actionRequest.getParameterValues("deleteItem");
		if(Validator.isNotNull(categoryId) && Validator.isNotNull(DelCategory))
			ShoppingCategoryServiceUtil.deleteCategory(categoryId);
		if(Validator.isNotNull(categoryIds)){
		for(int i=0; i<categoryIds.length; i++) {
			ShoppingCategoryServiceUtil.deleteCategory(Long.parseLong(categoryIds[i]));
		}
		}
		else{
			actionResponse.setRenderParameter("jspPage","/html/category/category_list.jsp"); 
		}
		
	}

	protected void updateCategory(ActionRequest actionRequest)
		throws Exception {

		long categoryId = ParamUtil.getLong(actionRequest, "categoryId", 0l);

		long parentCategoryId = ParamUtil.getLong(
			actionRequest, "parentCategoryId");
		String name = ParamUtil.getString(actionRequest, "name");
		String description = ParamUtil.getString(actionRequest, "description");

		boolean mergeWithParentCategory = ParamUtil.getBoolean(
			actionRequest, "mergeWithParentCategory");

		ServiceContext serviceContext = ServiceContextFactory.getInstance(
			ShoppingCategory.class.getName(), actionRequest);

		if (categoryId <= 0) {

			// Add category
			ShoppingCategoryServiceUtil.addCategory(
				parentCategoryId, name, description, serviceContext);
			 //actionResponse.setRenderParameter("jspPage", "/html/liferay/portlet/shopping/success.jsp");

		}
		else {

			// Update category
			ShoppingCategoryServiceUtil.updateCategory(
				categoryId, parentCategoryId, name, description,
				mergeWithParentCategory, serviceContext);
			//updateCustomField(actionRequest);
		}
	}
	
	protected void updateCustomField(ActionRequest actionRequest)
	throws Exception {
		
		int index = ParamUtil.getInteger(actionRequest, "index");
		long categoryId = ParamUtil.getLong(actionRequest, "categoryId");
		
		try {
			List<CustomField> list = (List) CustomFieldLocalServiceUtil.findByCategoryId(categoryId);
			for(CustomField field : list){
				CustomFieldLocalServiceUtil.deleteCustomField(field);
			}
		} catch(NoSuchCustomFieldException e) {}
		
		String formFieldsIndexes = ParamUtil.getString(actionRequest, "formFieldsIndexes");
		String[] fileds = formFieldsIndexes.split(",");
		
		for(int i = 0 ; i < fileds.length; i++) {
			CustomField entityImpl = new CustomFieldImpl();
			long recId= CounterLocalServiceUtil.increment("CustomField.class");
			entityImpl.setRecId(recId);
			String keyValue = ParamUtil.getString(actionRequest, "fieldLabel"+fileds[i]);
			String keyType = ParamUtil.getString(actionRequest, "fieldType"+fileds[i]);
			boolean optional = ParamUtil.getBoolean(actionRequest, "fieldOptional"+fileds[i]);
			String optionsValue = ParamUtil.getString(actionRequest, "fieldOptions"+fileds[i]);
			entityImpl.setCategoryId(categoryId);
			entityImpl.setKeyValue(keyValue);
			entityImpl.setKeyType(keyType);
			entityImpl.setOptional(optional);
			entityImpl.setOptionsValue(optionsValue);
			entityImpl.setFieldOrder(i+1);
			if(!keyValue.equals("")) CustomFieldLocalServiceUtil.addCustomField(entityImpl);
		}
		
	}
	
	private void categoryOrders(ActionRequest actionRequest,ActionResponse actionResponse) {
		// TODO Auto-generated method stub
	ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);			
	String name=ParamUtil.getString(actionRequest, "keywords");;
	try	{
	DynamicQuery dynamicQuery = DynamicQueryFactoryUtil.forClass(ShoppingCategory.class,PortalClassLoaderUtil.getClassLoader());
    if(Validator.isNotNull(name)) dynamicQuery.add(RestrictionsFactoryUtil.like("name","%"+name+"%"));
	List<ShoppingCategory> AdvanceSearchproject = ShoppingCategoryLocalServiceUtil.dynamicQuery(dynamicQuery);
	PortletSession session=actionRequest.getPortletSession();
	session.setAttribute("ADVANCE_SEARCH_PROJECT_LIST", AdvanceSearchproject);
	
	}catch(Exception ee){
		System.out.println("Exception Search Block"+ee);
	}
	}


}
